package handle

import (
	_ "fmt"
	"gitchina/CPTT4WeChat/data"
	"gitchina/CPTT4WeChat/protobuf"
	"gitchina/CPTT4WeChat/util"
	"github.com/golang/protobuf/proto"
)

type Garden struct {
	Name string `json:"name"`
}

func (g Garden) AddOrUpdate(p *protobuf.Garden) {
	var repo data.ApiRepo
	if info, ok := g.GetByUid(p.GetUid()); !ok {
		if _, err := repo.AddGarden(data.GardenDto{
			Name:      p.GetName(),
			Uid:       p.GetUid(),
			Signature: p.GetSignature(),
		}); err != nil {
			util.GetLogger().Error("[handle-AddOrUpdateGarden] - error: %s", err.Error())
		}
	} else {
		if p.GetSignature() != info.GetSignature() {
			if updated, err := repo.UpdateGarden(data.GardenDto{
				Id:        int(info.GetId()),
				Name:      p.GetName(),
				Signature: p.GetSignature(),
			}); err != nil {
				util.GetLogger().Error("[handle-AddOrUpdateGarden] - error: %s", err.Error())
			} else {
				if updated {
					if cache, ok := util.GetCache(util.Garden_Cache); ok {
						cache.Delete(p.GetUid())
					}
				}
			}
		}
	}
}

func (g Garden) GetByUid(uid string) (p *protobuf.Garden, ok bool) {
	var cache util.Cache
	var repo data.ApiRepo
	var val interface{}
	if cache, ok = util.GetCache(util.Garden_Cache); ok {
		if val, ok = cache.Get(uid); ok {
			p = val.(*protobuf.Garden)
		} else {
			if dto, err := repo.GetGardenByUid(uid); err == nil {
				p = &protobuf.Garden{
					Id:        proto.Int(dto.Id),
					Name:      proto.String(dto.Name),
					Uid:       proto.String(dto.Uid),
					Signature: proto.String(dto.Signature),
				}
				cache.Set(uid, p)
				ok = true
			} else {
				util.GetLogger().Error("[handle-GetGardenByUid] - error: %s", err.Error())
			}
		}
	}
	return
}
